//
//  WJYSearchViewController.h
//  WWLNetease
//
//  Created by dllo on 16/1/4.
//  Copyright © 2016年 Echo.Jobs. All rights reserved.
//

#import "WJYSearchViewController.h"

@interface WJYSearchViewController ()  <UITableViewDataSource, UITableViewDelegate, SearchCellDelegate, UISearchBarDelegate>

@property (nonatomic, retain) UISearchBar *searchBar; /**< 搜索框 */
@property (nonatomic, retain) UIButton *cancelButton; /**< 取消按钮 */
@property (nonatomic, retain) NSMutableArray *hotSearchArr; /**< 热词搜索数组 */
@property (nonatomic, retain) UITableView *tableView; /**< TableView */
@property (nonatomic, retain) NSMutableArray *searchDataArr; /**< 搜索数据数组 */
@property (nonatomic, retain) UITableView *searchTableView; /**< 搜索结果TableView */

@end

@implementation WJYSearchViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationItem.title =  @"搜索";
    
    
    // Do any additional setup after loading the view.
    [self searchHandleData];
    [self creatCancelButton];
    [self creatSearch];
    [self creatTableView];
    [self creatSearchTableView];
    
}

#pragma mark- 搜索入门
-(void)searchHandleData
{
    
    // AFN解析热词
    
    [AppTools getDataWithURL:@"http://c.3g.163.com/nc/search/hotWord.html" Block:^(id result) {
        
        // 将搜索结果存入数组
        NSArray *tempArr = [result objectForKey:@"hotWordList"];
        
        // 初始化数组
        self.hotSearchArr = [NSMutableArray array];
        
        // 遍历数组
        for (NSDictionary *dic in tempArr) {
            
            // 初始化
            WJYNewsModel *model = [[WJYNewsModel alloc] initWithDictionary:dic];
            
            // 添加进热词搜索数组
            [self.hotSearchArr addObject:model];
            
        }
        
        // 重载界面
        [self.tableView reloadData];

        
    } ErrorBlock:^(NSError *error) {
        
    }];
    
    
    
}

-(void)handleData
{
    
    // 拼接搜索字符串
    NSString *str = [self.searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet capitalizedLetterCharacterSet]];
    
    // 拼接网址
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/search/comp/MA==/20/%@.html?deviceId=MjY5NTJBNDEtMDIxMC00QjIxLUEwMTItMzFBRDk5REU2MDU0&version=NS4zLjQ=&channel=5aS05p2h", str];
    
    
    // AFNGET解析
    [AppTools getDataWithURL:url Block:^(id result) {
       
        // 取出数据存入字典
        NSDictionary *dic = [result objectForKey:@"doc"];
        
        // 取出数据存入数组
        NSArray *tempArr = [dic objectForKey:@"result"];
        
        // 搜索结果数组初始化
        self.searchDataArr = [NSMutableArray array];
        
        // 遍历数组
        for (NSDictionary *dicc in tempArr) {
            
            // 初始化
            WJYNewsModel *model = [[WJYNewsModel alloc] initWithDictionary:dicc];
            
            // 将Model添加至搜索结果数组
            [self.searchDataArr addObject:model];
            
            // 过滤掉有声模块
            if ([model.title hasPrefix:@"【<em>有声</em>】"]) {
                [self.searchDataArr removeObject:model];
            }
            
        }
        
        // 重载界面
        [self.searchTableView reloadData];
        
    } ErrorBlock:^(NSError *error) {
        
        
    }];
    
    
    
}

-(void)creatSearch
{
    
    // 初始化
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(SCREEN_FRAME.size.width / 20, 64, SCREEN_FRAME.size.width - SCREEN_FRAME.size.width / 5, SCREEN_FRAME.size.width / 10)];
    
    // 默认文字
    self.searchBar.placeholder = @"搜索";
    
    // 样式
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    
    // 协议
    self.searchBar.delegate = self;
    
    // 添加并并释放
    [self.view addSubview:self.searchBar];
    
    
}

-(void)creatCancelButton
{
    
    // 创建
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    // 标题
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    
    // 大小坐标
    self.cancelButton.frame = CGRectMake(SCREEN_FRAME.size.width / 1.25, 64, SCREEN_FRAME.size.width / 5, SCREEN_FRAME.size.width / 10);
    
    // 方法
    [self.cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchUpInside];
    
    // 添加到视图上
    [self.view addSubview:self.cancelButton];
    
    
}

#pragma mark- 取消按钮响应方法
-(void)cancelButton:(UIButton *)cancelButton
{
    
    // 返回
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
}

#pragma mark- 创建TableView
-(void)creatTableView
{
    
    // 初始化
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_FRAME.size.width / 20 + SCREEN_FRAME.size.width / 10 + 64, SCREEN_FRAME.size.width, SCREEN_FRAME.size.height) style:UITableViewStylePlain];
    
    // tag值
    self.tableView.tag = 100000;
    
    // 协议
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 不允许滚动
    self.tableView.scrollEnabled = NO;
    // 注册Cell
    [self.tableView registerClass:[WJYSearchTableViewCell class] forCellReuseIdentifier:@"search"];
    
    // 添加并释放
    [self.view addSubview:self.tableView];

    
}

#pragma mark- 创建搜索结果TableView
-(void)creatSearchTableView
{
    
    // 初始化
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_FRAME.size.width / 20 + SCREEN_FRAME.size.width / 10 + 64, SCREEN_FRAME.size.width, SCREEN_FRAME.size.height - 75 * SIZE) style:UITableViewStylePlain];
    
    // Tag值
    self.searchTableView.tag = 100001;
    
    // 协议
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    
    // footer初始化
    self.searchTableView.tableFooterView = [[UIView alloc] init];
    
    
    // 添加
    [self.view addSubview:self.searchTableView];
}



-(void)viewWillAppear:(BOOL)animated
{
    
    // 如果搜索框内容为空
    if (![self.searchBar.text isEqualToString:@""]) {
        
        // 搜索结果TableView隐藏
        self.tableView.hidden = YES;
        self.searchTableView.hidden = NO;
    } else {
        self.tabBarController.tabBar.hidden = YES;
        self.tableView.hidden = NO;
        self.searchTableView.hidden = YES;
    }
    
}

#pragma mark- 区数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // 区数
    if (tableView.tag == 100000) {
        return 2;
    } else {
        return self.searchDataArr.count;
    }
    
    
}

#pragma mark- 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        if (1 == indexPath.row) {
            return SCREEN_FRAME.size.height;
        } else {
            return SCREEN_FRAME.size.width / 10;
        }
        
    } else {
        
        return 60;
        
    }
    
}

#pragma mark- 创建Cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        if (0 == indexPath.row) {
            static NSString *str = @"qqq";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] ;
            }
            cell.textLabel.text = @"近期热点";
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:15];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        } else {
            WJYSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
            
            for (UIView *view in cell.contentView.subviews) {
                if (view) {
                    [view removeFromSuperview];
                }
            }
            
            cell.arr = self.hotSearchArr;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            return cell;
        }
    } else {
        NSLog(@"222222222");
        static NSString *str1 = @"www";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str1];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str1];
        }
        WJYNewsModel *model = [self.searchDataArr objectAtIndex:indexPath.row];
        
        NSString *str = model.title;
        
        // 去除无用字符
        str = [str stringByReplacingOccurrencesOfString:@"<em>" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"</em>" withString:@""];
        
        // 获取搜索框内容
        NSRange rang = [str rangeOfString:self.searchBar.text];
        
        // 字体颜色
        cell.textLabel.textColor = [UIColor grayColor];
        
        // 获取高亮字符串
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str];
        
        // 高亮字体颜色
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:rang];
        
        // 高亮字体
        cell.textLabel.attributedText = string;
        
        // 字体大小
        cell.textLabel.font = [UIFont systemFontOfSize:15 * SIZE];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView.tag == 100000) {
        [self.searchBar resignFirstResponder];
    } else {
        WJYNewsModel *model = [self.searchDataArr objectAtIndex:indexPath.row];
        
        if ([model.skipType isEqualToString:@"special"]) {
            
            WJYSpeicalViewController *special = [[WJYSpeicalViewController alloc] init];
            
            UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:special];
            
            special.specialID = model.docid;
            
            [self.navigationController pushViewController:naVC animated:YES];
            
        } else {
            
            WJYNewsModel *topLineM = [_searchDataArr objectAtIndex:indexPath.row];
            
            NewsViewController *newsVC = [[NewsViewController alloc] init];
            
            newsVC.docId = topLineM.docid;
            newsVC.newsTitle = topLineM.title;
            
            WJYNewsModel *topLineModel = [[WJYNewsModel alloc] init];
            
            topLineModel.title = topLineM.title;
            topLineModel.docid = topLineM.docid;
            
            newsVC.topLineModel = topLineModel;
            [self.navigationController pushViewController:newsVC animated:YES];
            
        }
    }
}

-(void)passValue:(NSString *)value
{
    
    self.searchBar.text = value;
    [self handleData];
    self.searchTableView.hidden = NO;
    self.tableView.hidden = YES;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    self.searchBar.text = searchText;
    if ([searchText isEqualToString:@""]) {
        self.tableView.hidden = NO;
        self.searchTableView.hidden = YES;
    } else {
        [self handleData];
        self.searchTableView.hidden = NO;
        self.tableView.hidden = YES;
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
